<?php
namespace common\wechat;
use yii\helpers\Url;

use common\wechat\interfaces\Ireply;
use common\tools\YWeChatPrint;
use common\models\AlbumAppModel;
use common\models\AlbumAppItemModel;
use editors\Uploader;

class ReplyImage implements Ireply
{
    protected $_postObject;
    protected $_fromUserName;
    protected $_toUserName;
    protected $_content;
    protected $_time;
    protected $_data;
    
    public function __construct($postObj) {
        // 获取参数   
        $this->_postObject = $postObj;
        $this->_time = time();      
        $this->_fromUserName = $this->_postObject->FromUserName;      
        $this->_toUserName =  $this->_postObject->ToUserName;      
        $this->_content = $this->_postObject->Content;          
    }
    
    public function createReMsg(){
        try{
            $aid = $this->doImageM();
            $url = \Yii::$app->params["weixinConf"]["domainName"]."/album/".$aid;
            $content = '成功上传一张图片，<a href="'.$url.'">点击开始制作</a>';  
        }catch(Exception $e){
            $content = $e->getMessage();  
        }          
        return YWeChatPrint::print_text($this->_fromUserName,$this->_toUserName,$content);       
    }
    private function doImageM(){
        //图片上传配置
        $config = array(
            "pathFormat" => "/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}",
            "maxSize" =>  2048000,
            "allowFiles" => [".png", ".jpg", ".jpeg", ".gif", ".bmp"],
            "oriName" => "remote.png"
        );    
        $albumAppModel = AlbumAppModel::getNewAlbumApp();
        $imageurl = $this->_postObject->PicUrl;
        $item     = new Uploader($imageurl, $config, "remote");
        $info     = $item->getFileInfo();
        if(isset($info["url"])){
            $albumAppItemModel         = new AlbumAppItemModel();
            $albumAppItemModel->app_id = $albumAppModel->id;
            $albumAppItemModel->openid = $albumAppModel->openid;
            $albumAppItemModel->pic    = $info["url"];
            if(!$albumAppItemModel->save()){
                 $error=array_values($albumAppItemModel->getFirstErrors())[0];
                 throw new Exception($error);//抛出异常
             }
        }else{
            throw new Exception("获取微信图片失败");//抛出异常
        }  
        return $albumAppModel->id;
    }
}
